//
//  LoopHomeViewController.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/6.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
import AFNetworking

let originalId = "LoopHomeTableViewCell"
let retweededId = "LoopRetweetedCell"
let homeTableCell = UINib(nibName: "LoopHomeTableViewCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LoopHomeTableViewCell
let retweetedTableCell = UINib(nibName: "LoopRetweetedCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LoopHomeTableViewCell

class LoopHomeViewController: LoopBaseViewController {
    
    lazy var homeViewModel:LoopHomeViewModel = LoopHomeViewModel()
    lazy var refresh:LoopHomeRefreshView = LoopHomeRefreshView()
    var isFristLoad = true
    lazy var lblTip:UILabel = {
    let lbl = UILabel(title: "", fontsize: 10, textColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))
        lbl.backgroundColor = UIColor.orange
        lbl.textAlignment = .center
        lbl.isHidden = true
        return lbl
    }()
    
    let homeTable:UITableView = {
        let home = UITableView(frame: UIScreen.main.bounds, style: .plain)
        return home
    }()

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        setupUI()
        
        setupTitle()
        
//        loadData()
        (self.tabBarController as! LoopTabBarController).reloadInfo = {
//            self.homeTable.setContentOffset(CGPoint(x: 0, y: -120), animated: true)
            self.homeTable.bounds = CGRect(x: 0, y: -120, width: screenWidth, height: screenHeight)
            self.loadData()
        }

    }
    
    func loadData(){
        homeViewModel.loadHomeData(isPull:activityView.isAnimating) { (isSuccess,count) in
            if !isSuccess{
                return
            }
            self.refresh.endRefreshing()
            if !self.activityView.isAnimating{
                self.startAnimation(count: count)
            }
            self.activityView.stopAnimating()
            self.isFristLoad = false
            self.homeTable.reloadData()
//            self.homeTable.refreshControl?.endRefreshing()
        }
    }
    
    //设置titleView
    private func setupTitle(){
        let title = LoopUserAccountViewModel.shared.userAccount?.name ?? ""
        let lblTitle = UILabel(title: title, fontsize: 14, textColor: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1))
        lblTitle.bounds = CGRect(x: 0, y: 0, width: 50, height: 30)
        self.navigationItem.titleView = lblTitle
    
    }
    
    //lblTip的动画
    private func startAnimation(count:Int){
        if lblTip.isHidden == false{
            return
        }
        lblTip.text = count == 0 ? "没有新的微博" : "更新\(count)条微博"
        lblTip.isHidden = false
        let originY = lblTip.frame.origin.y
    
        UIView.animate(withDuration: 1, animations: {
            self.lblTip.frame.origin.y = navigationHeigt
        }, completion: { (_) in
            
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
                self.lblTip.frame.origin.y = originY
            }, completion: { (_) in
                self.lblTip.isHidden = true
            })
            
        })
    }
    
    //设置整体页面
    override func setupUI(){
        super.setupUI()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navigationbar_pop"), style: .done, target: self, action: #selector(push))
        visitorV.changeInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
        
        //tableV的设置
        view.addSubview(homeTable)
        view.addSubview(lblTip)
        
        homeTable.dataSource = self
        homeTable.delegate = self
        homeTable.tableFooterView = activityView
        homeTable.separatorStyle = .none
//        homeTable.refreshControl = UIRefreshControl()
        homeTable.addSubview(refresh)
        refresh.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        lblTip.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 35)
        //两个Int类型不能进行减法操作
        lblTip.frame.origin.y = navigationHeigt - 35
        
        //单元格注册
        let originalCell:UINib = UINib(nibName: "LoopHomeTableViewCell", bundle: nil)
        homeTable.register(originalCell, forCellReuseIdentifier: originalId)
        let retweetedCell:UINib = UINib(nibName: "LoopRetweetedCell", bundle: nil)
        homeTable.register(retweetedCell, forCellReuseIdentifier: retweededId)
        
        loadData()
        registeNotification()
    }
    
    private func registeNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(changeTableFootView(noti:)), name: NSNotification.Name.AFNetworkingReachabilityDidChange, object: nil)
    }

    @objc private func changeTableFootView(noti:Notification){
        print("123-\(noti)")

    }

//    lazy var lblNoInternet:UILabel = {
//        let lbl = UILabel(title: <#T##String#>, fontsize: <#T##CGFloat#>, textColor: <#T##UIColor#>)
//    
//    }()
    
    //懒加载菊花控件
    internal lazy var activityView:UIActivityIndicatorView = {
        let activity = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        //测试菊花能不能转,记得关闭
//        activity.startAnimating()
        return activity
    }()
    
    @objc private func push() {
        self.navigationController?.pushViewController(LoopTestViewController(), animated: true)
    }
    
    
//    //获取数据
//    private func loadHomeData(finish:@escaping ([LoopStatus])->()){
//        
//        let urlString = "https://api.weibo.com/2/statuses/public_timeline.json"
//        let parameters = ["access_token" : LoopUserAccountViewModel.shared.userAccount?.access_token]
//        LoopNetWorkManager.shared.request(HTTPMethod: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil{
//                return
//            }
//            
//            let dic = responseObject as! [String : Any]
//            guard let array = dic["statuses"] as? [[String : Any]] else{
//            
//                SVProgressHUD.showError(withStatus: errorTip)
//                return
//            }
//            
//            var tempArray = [LoopStatus]()
//            for dict in array {
//            
//                let status = LoopStatus()
//                status.yy_modelSet(with: dict)
//                tempArray.append(status)
//                
//            }
//            finish(tempArray)
//        }
//    }
}

//Delegate && DataSource
extension LoopHomeViewController : UITableViewDataSource,UITableViewDelegate{
    //数据源方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.statusModelArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let status = homeViewModel.statusModelArray[indexPath.row]
        let cellId = chooseCellId(viewModel: status)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! LoopHomeTableViewCell
        cell.viewModel = status
        return cell
        
    }

    //根据所得数据中的字段,选择不同的cell
    private func chooseCellId(viewModel: LoopStatusCellViewModel)->String{
       return viewModel.statusModel?.retweeted_status != nil ? retweededId : originalId
    }
    
    
    
    //代理方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    //这个方法会在cell之前调用
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let status = homeViewModel.statusModelArray[indexPath.row]
//        print(status.rowHeight)
        return status.rowHeight
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        AFNetworkReachabilityManager.shared().startMonitoring()
        AFNetworkReachabilityManager.shared().setReachabilityStatusChange { (status) in
            print(status)
        }
        
//        let str = AFNetworkReachabilityManager.shared().localizedNetworkReachabilityStatusString()
//        print(str)
//        print(activityView.isAnimating)
        //静默加载的方式,可以让用户感觉的不到刷新
        if indexPath.row == homeViewModel.statusModelArray.count - 4 && activityView.isAnimating == false {
            activityView.startAnimating()
            loadData()
        }
    }
    
}
